package com.bkhech.netty.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class MessagePublisherTest {

    // 定义交换机的名字
    public static final String TEST_EXCHANGE = "test_exchange";

    // 定义队列的名字
    public static final String TEST_QUEUE = "test_queue";
    // 发送信息到消息队列的路由键
    public static final String TEST_ROUTING_KEY = "test.msg.send";

    public static void saveMessageByMQ(String msg) throws Exception {
        // 1. 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 1.1 设置连接参数
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setVirtualHost("test");
        factory.setUsername("test");
        factory.setPassword("123456");

        // 1.2 建立连接
        Connection connection = factory.newConnection();

        // 2. 创建通道channel
        Channel channel = connection.createChannel();

//         // 3. 定义队列
//         channel.queueDeclare(TEST_QUEUE,
//                             true,
//                             false,
//                             false,
//                             null);
//
//         // 4. 定义交换机
//         channel.exchangeDeclare(TEST_EXCHANGE,
//                 BuiltinExchangeType.FANOUT,
//                 true,
//                 false,
//                 null);

//         // 5. 交换机绑定队列
//         channel.queueBind(TEST_QUEUE, TEST_EXCHANGE, "");

        // 6. 发送消息
        channel.basicPublish(TEST_EXCHANGE,
                "",
                null,
                msg.getBytes());

        // 5. 关闭通道和连接
        channel.close();
        connection.close();
    }

    public static void main(String[] args) throws Exception {
        saveMessageByMQ("Send a chat msg by rabbitmq~~~  another  ");
    }
}
